/******************************************************************************\
    SubmitQueue.h contains a class of submit queue.
    It's used with acm server. See main.cpp for details.
    Copyright (C) 2008  Victor Vinogradov (fly3333@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/

#pragma once

#include <Common\BaseThread.h>
#include <queue>
#include <Common\CriticalSection.hpp>
#include <Common\Semaphore.hpp>
#include <Common\Event.hpp>

class cWardSubmitQueue : public cBaseThread
{
private:
	std::queue< unsigned long > Queue;
	cCriticalSection CriticalSection;
	cSemaphore Semaphore;
	cEvent TerminateEvent;
protected:
	virtual unsigned long Process();
public:
	cWardSubmitQueue();
	~cWardSubmitQueue();
	bool Enqueue( unsigned long submit_id );
	friend class cSubmitQueue;
};

class cSubmitQueue : public cPointerObject< cWardSubmitQueue >
{
public:
	bool Create()
	{
		cWardSubmitQueue *ward_submit_queue;
		try
		{
			ward_submit_queue = new cWardSubmitQueue();
		}
		catch( ... )
		{
			return false;
		}
		if( ward_submit_queue->Thread == INVALID_HANDLE_VALUE ||
			 ward_submit_queue->Thread.Resume() == -1 ||
			 !SwitchToWardObject( ward_submit_queue ) )
		{
			delete ward_submit_queue;
			return false;
		}
		return true;
	}
	void Destroy()
	{
		SwitchToSubObject( NULL );
	}
};
